package com.micro.school.order.controller;

import com.micro.school.common.core.constant.Constants;
import com.micro.school.common.core.constant.PayConstants;
import com.micro.school.common.core.context.SecurityContextHolder;
import com.micro.school.common.core.domain.R;
import com.micro.school.common.core.utils.StringUtils;
import com.micro.school.common.core.utils.poi.ExcelUtil;
import com.micro.school.common.core.web.controller.BaseController;
import com.micro.school.common.core.web.domain.AjaxResult;
import com.micro.school.common.core.web.page.TableDataInfo;
import com.micro.school.order.entity.PayFeeItemConfig;
import com.micro.school.order.entity.PayOrderImport;
import com.micro.school.order.entity.PayOrderImportRecord;
import com.micro.school.order.entity.PayStudentFee;
import com.micro.school.order.service.IPayFeeItemConfigService;
import com.micro.school.order.service.IPayStudentFeeService;
import com.micro.school.order.service.PayOrderImportRecordService;
import com.micro.school.order.service.PayOrderImportService;
import com.micro.school.order.utils.FileDownloadUtil;
import com.micro.school.order.vo.PayStudentFeeVo;
import com.micro.school.system.api.RemoteEduService;
import com.micro.school.system.api.RemoteUserService;
import com.micro.school.system.api.domain.StudentInfos;
import com.micro.school.system.api.domain.vo.*;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Future;


@RequestMapping("/payOrderImport")
@RestController
public class PayOrderImportController extends BaseController {

    @Resource
    private PayOrderImportService payOrderImportService;

    @Resource
    private PayOrderImportRecordService payOrderImportRecordService;

    @Resource
    private IPayFeeItemConfigService payFeeItemConfigService;

    @Autowired
    private RemoteEduService remoteEduService;

    @Resource
    private RemoteUserService remoteUserService;

    @Resource
    private IPayStudentFeeService payStudentFeeService;

    /**
     * 查询人工订单列表
     */
    @GetMapping("/list")
    public TableDataInfo list(PayOrderImport payOrderImport) {
        startPage();
        if (!SecurityContextHolder.getUserName().equals("admin")) {
            payOrderImport.setCreateBy(SecurityContextHolder.getUserName());
        }

        List<PayOrderImport> list = payOrderImportService.selectPayOrderImportList(payOrderImport);
        return getDataTable(list);
    }

    /**
     * 上传人工订单列表
     */
    @PostMapping("upload")
    public AjaxResult upload(MultipartFile file, HttpServletResponse response) throws Exception {
        try {
            ExcelUtil<PayOrderImportRecord> util = new ExcelUtil<>(PayOrderImportRecord.class);
            List<PayOrderImportRecord> uploadVos = util.importExcel(file.getInputStream());

            if (file.isEmpty()) {
                return error("请上传文件");
            }
            // 验证Excel模板是否正确（检查表头）
            if (!isValidTemplate(file.getInputStream())) {
                return error("模板不正确，请重新下载");
            }
            // 启动异步处理
            Future<String> future = processExcelUpload(file.getInputStream(), file.getOriginalFilename());

            // 返回立即响应，告知客户端已开始处理
            return success("文件上传成功，正在后台处理中，请稍后查看结果");
        } catch (Exception e) {
            logger.error("文件上传失败", e);
            return error("上传失败: " + e.getMessage());
        }
    }

    /**
     * 异步处理Excel上传
     */
    public Future<String> processExcelUpload(InputStream inputStream, String originalFilename) {
        try {
            ExcelUtil<PayOrderImportRecord> util = new ExcelUtil<>(PayOrderImportRecord.class);
            List<PayOrderImportRecord> uploadVos = util.importExcel(inputStream);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
            String batchId = simpleDateFormat.format(new Date());
            PayOrderImport payOrderImport = new PayOrderImport();
            payOrderImport.setCreateTime(new Date());
            payOrderImport.setCreateBy(SecurityContextHolder.getUserName());
            payOrderImport.setBatchNum(batchId);
            payOrderImport.setUpdateTime(new Date());
            payOrderImport.setUpdateBy(SecurityContextHolder.getUserName());
            payOrderImport.setTenantId(SecurityContextHolder.getUserTenantId());
            payOrderImport.setDeleteFlag("0");

            int errorCount = 0;

            for (PayOrderImportRecord info : uploadVos) {
                // 基础字段验证
                validateBasicFields(info);
                // 如果基础验证失败，跳过后续验证
                if (info.getErrorMsg() != null && !info.getErrorMsg().isEmpty()) {
                    errorCount++;
                    prepareRecordForSave(info, batchId, payOrderImport, false);
                    continue;
                }
                // 关联数据验证
                boolean isValid = validateRelatedData(info, payOrderImport);

                if (!isValid) {
                    errorCount++;
                }

                // 准备保存记录
                prepareRecordForSave(info, batchId, payOrderImport, isValid);
            }

            // 设置导入状态
            payOrderImport.setImportStatus(errorCount > 0 ? 20 : 10);

            // 保存数据
            String status = payOrderImportRecordService.insertPayOrderImportRecord(uploadVos, payOrderImport);
            payOrderImportService.insertOrderImport(payOrderImport, status);

            return new AsyncResult<>("上传成功");
        } catch (Exception e) {
            logger.error("文件上传失败", e);
            return new AsyncResult<>("上传失败: " + e.getMessage());
        }
    }


    /**
     * 验证Excel模板是否正确（检查表头）
     * @param inputStream Excel文件输入流
     * @return 模板是否正确
     */
    private boolean isValidTemplate(InputStream inputStream) {

        try {
            ExcelUtil<PayOrderImportRecord> util = new ExcelUtil<>(PayOrderImportRecord.class);
            // 获取Excel的表头信息
            String[] headers = util.importExcelHeaders(inputStream);

            if (headers == null || headers.length == 0) {
                return false;
            }

            // 定义必须包含的表头字段
            String[] requiredHeaders = {
                    "姓名", "学院名称", "模式", "专业名称", "年级", "学年", "收费项目","收费金额","身份证号"
            };

            // 检查是否包含所有必需的表头
            for (String requiredHeader : requiredHeaders) {
                boolean found = false;
                for (String header : headers) {
                    if (requiredHeader.equals(header)) {
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    return false;
                }
            }

            return true;
        } catch (Exception e) {
            logger.error("验证模板表头时出错", e);
            return false;
        }
    }

    /**
     * 基础字段验证
     */
    private void validateBasicFields(PayOrderImportRecord info) {
        if (StringUtils.isEmpty(info.getModelName())) {
            info.setErrorMsg("模式不能为空！");
        } else if (StringUtils.isEmpty(info.getCollegeName())) {
            info.setErrorMsg("学院不能为空！");
        } else if (StringUtils.isEmpty(info.getMajorName())) {
            info.setErrorMsg("专业不能为空！");
        } else if (StringUtils.isEmpty(info.getGradeName())) {
            info.setErrorMsg("年级不能为空！");
        } else if (StringUtils.isEmpty(info.getStudentName())) {
            info.setErrorMsg("姓名不能为空！");
        } else if (StringUtils.isEmpty(info.getIdNumber())) {
            info.setErrorMsg("身份证号不能为空！");
        } else if (info.getIdNumber().length() != 18) {
            info.setErrorMsg("身份证号必须为18位");
        } else if (StringUtils.isEmpty(info.getFeeYear())) {
            info.setErrorMsg("学年不能为空！");
        } else if (StringUtils.isEmpty(info.getFeeItemConfigName())) {
            info.setErrorMsg("收费项目不能为空！");
        } else if (info.getItemPrice() == null) {
            info.setErrorMsg("收费金额不能为空！");
        }
    }

    /**
     * 关联数据验证
     */
    private boolean validateRelatedData(PayOrderImportRecord info, PayOrderImport payOrderImport) {
        try {
            // 验证学院信息
            SchoolCollegeVos schoolCollegeVos = new SchoolCollegeVos();
            schoolCollegeVos.setCollegeName(info.getCollegeName());
            schoolCollegeVos.setDeleteFlag("0");
            schoolCollegeVos.setStatus("1");
            R<List<SchoolCollegeVos>> collegeResult = remoteEduService.checkCollege(schoolCollegeVos);

            if (collegeResult.getData() == null || collegeResult.getData().isEmpty()) {
                info.setErrorMsg("学院不存在");
                return false;
            }

            SchoolCollegeVos college = collegeResult.getData().get(0);
            info.setCollegeId(String.valueOf(college.getId()));
            payOrderImport.setCampusId(college.getCampusId());

            // 验证学生信息
            StudentInfoVos studentInfoVos = new StudentInfoVos();
            studentInfoVos.setName(info.getStudentName());
            studentInfoVos.setIdNumber(info.getIdNumber());
            studentInfoVos.setIsDel(0);
            R<StudentInfos> studentResult = remoteUserService.queryStudent(studentInfoVos);

            if (studentResult.getData() == null) {
                info.setErrorMsg("学生不存在");
                return false;
            }

            StudentInfos student = studentResult.getData();
            info.setStudentId(student.getId());
            info.setSex(String.valueOf(student.getSex()));
            info.setSchoolSystem(student.getSchoolSystem());

            // 验证培养模式
            CollegeModelVos collegeModelVos = new CollegeModelVos();
            collegeModelVos.setModelName(info.getModelName());
            collegeModelVos.setCollegeName(info.getCollegeName());
            collegeModelVos.setCampusId(college.getCampusId());
            collegeModelVos.setDeleteFlag("0");
            collegeModelVos.setStatus("1");
            R<List<CollegeModelVos>> modelResult = remoteEduService.checkEducation(collegeModelVos);

            if (modelResult.getData() == null || modelResult.getData().isEmpty()) {
                info.setErrorMsg("模式不存在");
                return false;
            }

            info.setModelId(String.valueOf(modelResult.getData().get(0).getId()));

            // 验证专业信息
            CollegeMajorVos collegeMajorVos = new CollegeMajorVos();
            collegeMajorVos.setCollegeIds(String.valueOf(college.getId()));
            collegeMajorVos.setMajorName(info.getMajorName());
            collegeMajorVos.setDeleteFlag("0");
            collegeMajorVos.setStatus("1");
            collegeMajorVos.setModelId(modelResult.getData().get(0).getId());
            R<List<CollegeMajorVos>> majorResult = remoteEduService.checkMajor(collegeMajorVos);

            if (majorResult.getData() == null || majorResult.getData().isEmpty()) {
                info.setErrorMsg("专业不存在");
                return false;
            }

            info.setMajorId(String.valueOf(majorResult.getData().get(0).getId()));

            // 验证年级信息
            SchoolGradeVos schoolGradeVos = new SchoolGradeVos();
            schoolGradeVos.setGrade(info.getGradeName());
            schoolGradeVos.setDeleteFlag("0");
            schoolGradeVos.setStatus("1");
            R<List<SchoolGradeVos>> gradeResult = remoteEduService.checkGrade(schoolGradeVos);

            if (gradeResult.getData() == null || gradeResult.getData().isEmpty()) {
                info.setErrorMsg("年级不存在");
                return false;
            }

            info.setGradeId(String.valueOf(gradeResult.getData().get(0).getId()));

            // 验证收费项目
            PayFeeItemConfig payFeeItemConfig = new PayFeeItemConfig();
            payFeeItemConfig.setItemName(info.getFeeItemConfigName());
            payFeeItemConfig.setTenantId(Integer.valueOf(SecurityContextHolder.getUserTenantId()));
            payFeeItemConfig.setCloseStatus(PayConstants.YESORNO_Y);
            payFeeItemConfig.setDeleteFlag("0");
            List<PayFeeItemConfig> feeItemConfigs = payFeeItemConfigService.selectPayFeeItemConfigList(payFeeItemConfig);

            if (feeItemConfigs == null || feeItemConfigs.isEmpty()) {
                info.setErrorMsg("不存在该收费项目");
                return false;
            }

            PayFeeItemConfig feeItem = feeItemConfigs.get(0);
            info.setFeeItemConfigType(feeItem.getSubjectType());
            info.setMandatoryStatus(feeItem.getMandatoryStatus());

            // 验证学年
            SchoolFeeYearVos schoolFeeYearVos = new SchoolFeeYearVos();
            schoolFeeYearVos.setDeleteFlag("0");
            schoolFeeYearVos.setTenantId(Long.valueOf(SecurityContextHolder.getUserTenantId()));
            schoolFeeYearVos.setStatus("1");
            schoolFeeYearVos.setIsCloseChannel("1");
            schoolFeeYearVos.setFeeYear(info.getFeeYear());
            R<List<SchoolFeeYearVos>> feeYearResult = remoteEduService.checkFeeYear(schoolFeeYearVos);

            if (feeYearResult.getData() == null || feeYearResult.getData().isEmpty()) {
                info.setErrorMsg("不存在该学年");
                return false;
            }

            info.setFeeYearId(Math.toIntExact(feeYearResult.getData().get(0).getId()));

            // 验证是否已存在支付订单
            PayStudentFee payStudentFee = new PayStudentFee();
            payStudentFee.setStudentName(info.getStudentName());
            payStudentFee.setIdNumber(info.getIdNumber());
            payStudentFee.setFeeYear(info.getFeeYear());
            payStudentFee.setTenantId(Integer.valueOf(SecurityContextHolder.getUserTenantId()));
            List<PayStudentFeeVo> existingOrders = payStudentFeeService.selectPayStudent(payStudentFee);

            if (existingOrders != null && !existingOrders.isEmpty()) {
                info.setErrorMsg("该学生该学年订单已支付过，请勿重新导入");
                return false;
            }

            return true;
        } catch (Exception e) {
            logger.error("验证关联数据时出错", e);
            info.setErrorMsg("系统验证出错: " + e.getMessage());
            return false;
        }
    }

    /**
     * 准备记录保存数据
     */
    private void prepareRecordForSave(PayOrderImportRecord info, String batchId,
                                      PayOrderImport payOrderImport, boolean isValid) {
        info.setBatchNum(batchId);
        info.setImportStatus(isValid ? 10 : 20);
        info.setCreateTime(new Date());
        info.setUpdateTime(new Date());
        info.setCreateBy(SecurityContextHolder.getUserName());
        info.setUpdateBy(SecurityContextHolder.getUserName());
        info.setTenantId(SecurityContextHolder.getUserTenantId());
        info.setDeleteFlag("0");
        // 设置校区ID（如果存在）
        if (payOrderImport.getCampusId() != null) {
            info.setCampusId(payOrderImport.getCampusId());
        }
    }




    /**
     * 重新上传人工订单列表
     */
    @GetMapping("repeatUpload/{batchId}")
    public AjaxResult repeatUpload(@PathVariable String batchId) throws Exception{
        String message = payOrderImportService.repeatUpload(batchId);
        return AjaxResult.success(message);

    }


    /**
     * 下载人工订单列表
     */
    @PostMapping("/download")
    public void downloadTemplate(HttpServletResponse response) {
        try {
            FileDownloadUtil.downloadExcelTemplate(
                    "static/工程大学人工订单导入模板.xlsx",
                    "工程大学人工订单导入模板.xlsx",
                    response
            );
        } catch (IOException e) {
            e.printStackTrace();
            try {
                response.getWriter().write("模板文件下载失败: " + e.getMessage());
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }

}
